package com.jiangnan.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jiangnan.entity.ChatMessage
import com.jiangnan.entity.ChatRequest
import com.jiangnan.repository.DeepSeekRepository
import kotlinx.coroutines.launch

class DeepSeekViewModel(private val repository: DeepSeekRepository) : ViewModel() {

    private val _streamResponse = MutableLiveData<String>()
    val streamResponse: LiveData<String>
        get() = _streamResponse

    init {
        // 如果这里设置了 _streamResponse.value = "正在思考..."
        // 那就会导致初始直接显示聊天区
        _streamResponse.value = "" // 确保初始为空
    }

    // 发送流式请求
    fun sendChatStreamRequest(userInput: String) {
        val messages = listOf(
            ChatMessage(
                role = "user",
                content = userInput
            )
        )
        val request = ChatRequest(
            model = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B",
            stream = true,
            max_tokens = 2048,
            temperature = 0.7,
            top_p = 0.7,
            top_k = 50,
            frequency_penalty = 0.5,
            n = 1,
            messages = messages
        )
        // 如果首次发送，先显示“正在思考回复中…”
        if (_streamResponse.value.isNullOrEmpty()) {
            _streamResponse.value = "正在思考回复中...\n[问题]：$userInput\n"
        } else {
            // 如果之前已经有内容，追加分隔符
            _streamResponse.value = _streamResponse.value + "\n\n[新问题]：$userInput\n正在思考回复中...\n"
        }

        viewModelScope.launch {
            repository.streamChatResponse(request).collect { chunk ->
                // 累计追加每一块文本
                _streamResponse.value = (_streamResponse.value ?: "") + chunk
            }
        }
    }

    // 清空聊天内容
    fun clearChat() {
        _streamResponse.value = ""
    }
}
